package org.emf.plugins.tomcatlauncher.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.emf.plugins.tomcatlauncher.server.KyahRequest.Command;

/**
 * Represents the Kyah client.
 */
public class KyahClient {

    /** It will always be localhost. Not dealing with remote servers. */
    private static final String HOST = "localhost";

    /** Socket that provides teh communication. */
    private Socket socket;

    /** Communication channel created based on socket connection. */
    private CommChannel channel;

    /**
     * Sends a command to the server.
     * @param command {@link Command} to be sent.
     * @return the response as a result of the command being sent.
     * @throws UnknownHostException if host is unknown.
     * @throws IOException if communication fails.
     */
    public KyahResponse sendMessage(Command command) throws UnknownHostException, IOException {
        return channel.sendCommand(command);
    }

    /**
     * Opens a connection with the server.
     * @return the response as result of connection opened.
     * @throws UnknownHostException if host is unknown.
     * @throws IOException if communication fails.
     */
    public KyahResponse connect() throws UnknownHostException, IOException {
        socket = new Socket(HOST, CommChannel.SERVER_PORT);
        channel = new CommChannel(
                new BufferedReader(new InputStreamReader(socket.getInputStream())),
                new PrintWriter(socket.getOutputStream(), true));
        return channel.readResponse();
    }

    /**
     * Closes communication and client itself.
     * @throws IOException if communication fails.
     */
    public void close() throws IOException {
        channel.close();
        socket.close();
    }
}
